import os
import time
import uuid
import random

from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from werkzeug.utils import secure_filename

from database import db
from modal import User, Model, Theme, Preset
from utils import fail_api, auto_model_jsonify

bp = Blueprint('form', __name__, url_prefix='/form')


@bp.post('')
@jwt_required()
def gen_videos():
    data = request.json
    model_id = data.get('model')

    if not model_id:
        return fail_api(msg='请选择模型')

    # todo 校验图片和提示词不能为空

    model = Model.query.filter_by(id=model_id).first()
    current_user = get_jwt_identity()
    user = User.query.filter_by(email=current_user).first()

    if model.cost > user.amount:
        return fail_api(msg='余额不足')
    user.amount -= model.cost
    db.session.commit()

    previews = [model.preview for model in Model.query.filter(Model.preview != '').all()]

    num = random.randint(1, 5)
    previews = random.sample(previews, num)

    time.sleep(1)
    return previews


@bp.get('/model')
def model():
    return auto_model_jsonify(model=Model, data=Model.query.all())


@bp.get('/preset')
def preset():
    themes = Theme.query.all()

    result = []
    for theme in themes:
        presets = Preset.query.filter_by(theme_id=theme.id).all()

        preset_list = []
        for preset_item in presets:
            preset_list.append(auto_model_jsonify(model=Preset, data=preset_item))

        theme_data = {
            "id": theme.id,
            "name": theme.name,
            "presets": preset_list
        }
        result.append(theme_data)
    return jsonify(result)


ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'webp', 'gif', 'heic'}
UPLOAD_FOLDER = 'files'
MAX_FILE_SIZE = 20 * 1024 * 1024  # 20 MB


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def check_file_size(file):
    current_position = file.tell()
    file.seek(0, 2)
    file_size = file.tell()
    file.seek(current_position)
    return file_size <= MAX_FILE_SIZE


@bp.post('/upload')
def upload_image():
    file = request.files['file']

    if file and allowed_file(file.filename):
        if not check_file_size(file):
            return fail_api(msg=f'文件大小超过限制，最大支持{MAX_FILE_SIZE // (1024 * 1024)}MB')

        # 生成安全的文件名
        filename = secure_filename(file.filename)
        # 生成唯一文件名避免冲突
        unique_filename = f"{uuid.uuid4().hex}_{filename}"

        if not os.path.exists(UPLOAD_FOLDER):
            os.makedirs(UPLOAD_FOLDER)

        file_path = os.path.join(UPLOAD_FOLDER, unique_filename)
        file.save(file_path)

        base_url = request.host_url.rstrip('/')  # 获取当前请求的基础URL
        file_url = f"{base_url}/files/{unique_filename}"

        return jsonify({
            'url': file_url,
            'filename': unique_filename,
            'original_filename': filename,
            'file_size': os.path.getsize(file_path)
        })
    else:
        allowed_extensions = ', '.join(ALLOWED_EXTENSIONS)
        return fail_api(msg=f'不支持的文件类型，请上传 {allowed_extensions} 格式的图片')
